var netWork = require('../../../utils/netWork.js');
var api = require('../../../utils/api.js');
var openApiCode = require('../../../utils/openApiCode.js');
const log = require('../../../utils/logs.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagesUrl: getApp().globalData.imagesUrl,
    topHeight: 0, //顶部高度
    isShowModalRule: false,
    ani: 0,
    retCode: "", //错误代码
    retMsg: "", //错误描述
    servicePhone: "" //客服电话
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    log.info('[prompt]--->[onLoad]' + JSON.stringify(options))
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    try {
      const {
        SDKVersion = ''
      } = wx.getSystemInfoSync();
      log.info(SDKVersion)
      const compatibility = util.compareVersion(SDKVersion, '2.2.2');
      log.info(compatibility)
      if (compatibility == -1) {
        wx.showModal({
          content: '您的微信版本过低，请升级后再来吧~',
          confirmText: '我知道了',
          showCancel: false
        });
        return;
      }
    } catch (e) {}
    try {
      // 检测是否可以调用getUpdateManager检查更新
      if (!wx.canIUse("getUpdateManager")) return;
      let updateManager = wx.getUpdateManager();
      // 获取全局唯一的版本更新管理器，用于管理小程序更新
      updateManager.onCheckForUpdate(function (res) {
        log.info(res)
        // 监听向微信后台请求检查更新结果事件
        log.info("是否有新版本：" + res.hasUpdate);
        if (res.hasUpdate) {
          //如果有新版本
          // 小程序有新版本，会主动触发下载操作
          updateManager.onUpdateReady(function () {
            //当新版本下载完成，会进行回调
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，单击确定重启小程序',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序
                  updateManager.applyUpdate();
                }
              }
            })
          })
          // 小程序有新版本，会主动触发下载操作（无需开发者触发）
          updateManager.onUpdateFailed(function () {
            //当新版本下载失败，会进行回调
            wx.showModal({
              title: '提示',
              content: '检查到有新版本，但下载失败，请稍后尝试',
              showCancel: false,
            })
          })
        }
      });
    } catch (e) {
      e
    }
    // api.showLoading('正在加载中...')
    let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
    this.setData({
      topHeight: topHeight
    });
    if (options.notWinning) {
      this.setData({
        notWinning: options.notWinning
      })
    }
    this.setData({
      retCode: options.retCode == undefined || options.retCode == 'undefined' || options.retCode == '' ? openApiCode.UNDEFINED.code : options.retCode,
      retMsg: options.retMsg == undefined || options.retMsg == 'undefined' || options.retMsg == '' ? openApiCode.UNDEFINED.msg : options.retMsg,
      servicePhone: wx.getStorageSync('servicePhone')
    })
    if (options.nickName) {
      this.setData({
        nickName: options.nickName,
      })
    }
    if (options.luckyTime) {
      this.setData({
        luckyTime: options.luckyTime,
      })
    }


  },
  /**
   * 拨打客服电话
   */
  callPhone: function () {
    let that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.servicePhone //客服电话
    })
  },
  /**
   *查询是否关注公众号
   */
  queryIsFollow: function () {
    const that = this;
    netWork.POST('searchUserInfo', {
      data: {
        userId: wx.getStorageSync('userId')
      },
      success: function (res) {
        api.cancelLoading();
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == "0000") {
          if (res.data.data.isFollow == 1) { //关注
            //跳转中奖记录
            wx.redirectTo({
              url: '../prizeRecord/prizeRecord',
            })
          } else { //未关注，引导关注
            wx.navigateTo({
              url: '../officialAccount/officialAccount',
            })
          }

        } else { //失败，暂时不按未关注处理

        }
      },
      fail: function () {
        // wx.redirectTo({
        //   url: '../../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
        // })
      }
    });
  },
  /**
   * 跳转中奖记录页面
   */
  showPrizeRecord: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    this.queryIsFollow();
  },
  // copyPhone: function () {
  //   var that = this;
  //   wx.setClipboardData({
  //     //准备复制的数据
  //     data: that.data.servicePhone,
  //     success: function (res) {
  //       wx.showToast({
  //         title: '复制成功',
  //         icon: 'none'
  //       });
  //     }
  //   });
  // },
  /**
   * 显示活动规则
   */
  showRule: function () {
    wx.navigateTo({
      url: '../ruleh5/ruleh5'
    })
  },
  onReady: function () {
    api.cancelLoading()
  },
  /**
   * 关闭活动规则
   */
  clickClose: function () {
    this.setData({
      ani: 1
    })
    const that = this;
    setTimeout(function () {
      that.setData({
        isShowModalRule: false
      })
    }, 180);
  },
/**
   * 更多活动， 跳转第三方小程序
   */
  showMore: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    this.queryIsFollowGG();
  },

/**
   *查询是否关注公众号
   */
  queryIsFollowGG: function () {
    const that = this;
    netWork.POST('searchUserInfo', {
      data: {
        userId: wx.getStorageSync('userId')
      },
      success: function (res) {
         
        if (res.data.retCode == undefined) {
          wx.redirectTo({
            url: '../prompt/prompt?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
          })
        }
        if (res.data.retCode == "0000") {
          if (res.data.data.isFollow == 1) { //关注
            //跳转中奖记录
            wx.navigateToMiniProgram({
              appId: api.thirdAppId,
              envVersion:getApp().globalData.ganguoAppidStyle
            })
          } else { //未关注，引导关注
            wx.navigateTo({
              url: '../officialAccount/officialAccount',
            })
          }

        } else { //失败，暂时不按未关注处理
          //跳转中奖记录
          wx.navigateToMiniProgram({
            appId: api.thirdAppId,
            path: 'pages/home/home',
            envVersion:getApp().globalData.ganguoAppidStyle
          })
        }
      },
      fail: function () {
        //跳转中奖记录
        wx.navigateToMiniProgram({
          appId: api.thirdAppId,
          path: 'pages/home/home',
          envVersion:getApp().globalData.ganguoAppidStyle
        })
      }
    });
  },
  scanQcord: function () {
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    api.scanCode();
  },
  back(){
    //清空缓存
    wx.removeStorageSync('qrCode');
    wx.removeStorageSync('prizeList');
    wx.removeStorageSync('isShowPrizes');
    wx.navigateTo({
      url: '../index/index',
    })
  }
})